# app.py
from flask import Flask, jsonify, request
from models import db, EquipmentDomain, Equipment
import json

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///equipment.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

# 查询所有设备
@app.route('/api/equipments', methods=['GET'])
def get_equipments():
    equipments = Equipment.query.all()
    result = []
    for eq in equipments:
        result.append({
            'id': eq.id,
            'equip_name': eq.equip_name,
            'equip_type': eq.equip_type,
            'equip_user': eq.equip_user,
            'update_log': json.loads(eq.update_log)  # 反序列化日志
        })
    return jsonify(result)

# 新增设备
@app.route('/api/equipments', methods=['POST'])
def add_equipment():
    data = request.json
    new_equip = Equipment(
        equip_name=data.get('equip_name', ''),
        equip_type=data.get('equip_type', ''),
        equip_user=data.get('equip_user', ''),
        update_log=json.dumps(data.get('update_log', []))
    )
    db.session.add(new_equip)
    db.session.commit()
    return jsonify({'msg': '设备添加成功', 'id': new_equip.id})

if __name__ == '__main__':
    app.run(debug=True)  # 启动服务，默认端口5000
